<?php

namespace app\userweb\controller;

use think\Cookie;
use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;
use app\Base;
use ucpaas\SendMsg;
use \think\Validate;

class Login
{
    /**
     * @writer:leijie
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 用户注册
     * @return array|Json
     */
    public function registered(){
        $data = Request::instance()->post();
        // 判断手机号是否已注册
        $phoneNum   = $data['account'];
        $user       = Db::table('user')->where(['account'=>$phoneNum])->count();
        $supplier   = Db::table('supplier')->where('account',$phoneNum)->count();
        if ($user>0 || $supplier>0){
            $result['status']   = 220;
            $result['msg']      = "手机号已注册!";
        }else{
            try{
                $code = $data['code'];
                $sendCode = Session::get($phoneNum);
                //对比验证码
                if ($sendCode == $code){
                    if($data['invite'] != ''){
                        $c = Db::table('xw_invite_code')->where('i_code',$data['invite'])->find();
                        if(empty($c)){
                            return json(['status'=>230,'msg'=>'邀请码错误']);
                        }else{
                            Db::table('xw_invite_code')->where('i_id',$c['i_id'])->setInc ('i_num',1);
                        }
                    }
                    $data['registration_time'] = date('Y-m-d H:i:s',time());
                    // 加密密码
                    $data['password']       = md5($data['password']);
                    $data['is_complete']    = 0;
                    $re = Db::name('user')
                        ->strict(false)
                        ->insert($data);
                    if ($re){
                        $result = Config::get('code.success');
                        $result['data']['account'] = $phoneNum;
                    }else{
                        $result = Config::get('code.error');
                    }
                }else{
                    $result = Config::get('code.error');
                    $result['msg'] = "验证码错误";
                }
            }catch (\Exception $ex){
                $result = config('code.miss');
                $result['data'] = [];
            }
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 发送验证码
     * @return array|Json
     */
    public function codeGet(){
        $data = Request::instance()->post();
        if (!empty($data['account']) && !empty($data['type'])){
            $phoneNum = $data['account'];
            if ($data['type'] !=='register' && $data['type'] !=='unregistered'){
                $result = Config::get('code.mistake');
                $result['msg'] = "类型不对";
                return json($result);
            }
            // 判断请求场合
            if ('register' == $data['type']){
                // 注册请求
                $user = Db::name('user')
                    ->where(['account'=>$phoneNum])
                    ->count();
                $supplier = Db::name('supplier')
                    ->where(['account'=>$phoneNum])
                    ->count();
                if ($user>0 || $supplier>0){
                    $result = Config::get('code.error');
                    $result['msg'] = "手机号已注册!";
                    return json($result);
                }
            }elseif('unregistered' == $data['type']){
                // 已注册请求
                $user = Db::name('user')
                    ->where(['account'=>$phoneNum])
                    ->count();
                if ($user==0){
                    $result = Config::get('code.error');
                    $result['msg'] = "手机号未注册!";
                    return json($result);
                }
            }
            $code = codeRange(6);
            $msmRes = json_decode(SendMsg($phoneNum,$code),true);
            if ('000000' !== $msmRes['code']){
                //发送失败
                $result = Config::get('code.error');
                $result['data']['account'] = $phoneNum;
                $result['data']['code'] = $code;
                $result['msg'] = "发送失败";
            }else{
                Session::set($phoneNum,$code);
                $result = Config::get('code.success');
                $result['data']['account'] = $phoneNum;
                $result['data']['code'] = $code;
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }


    /**
     * @writer:leijie
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 用户密码登录
     * @return array|Json
     */
    public function login(){
        $data = Request::instance()->post();
        if (!empty($data['account']) && !empty($data['password']) && !empty($data['type'])){
            // 判断账号是否存在
            $user = Db::name('user')
                ->where(['account'=>$data['account']])
                ->count();
            if($user==0){
                $result = Config::get('code.null');
                $result['msg'] = "账号不存在，请重新填写";
                return json($result);
            }
            // 密码加密
            $password = md5($data['password']);
            $re = Db::name('user')
                ->where(['account'=>$data['account'],'password'=>$password])
                ->find();
            if ($re){
                // 生成新的token
                if ('APP' == $data['type']){
                    $token['app_token'] = randomNum();
                }else if ('WEB' == $data['type']){
                    $token['web_token'] = randomNum();
                }
                Db::name('user')->where(['id'=>$re['id']])->update(['web_token' => $token['web_token']]);
                $result = Config::get('code.success');
                $result['data']         = $re;
                $result['web_token']    = $token['web_token'];
            }else{
                $result = Config::get('code.error');
                $result['msg'] = "账号或密码错误";
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 设置密码
     * @return array|Json
     */
    public function pwdSet(){
        $data = Request::instance()->post();
        if (!empty($data['account']) && !empty($data['password'])){
            // 默认前端密码已确认2次输入一致,加密密码
            $data['password'] = md5($data['password']);
            $re = Db::name('user')
                ->where(['account'=>$data['account']])
                ->setField('password',$data['password']);
            if ($re){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 完善注册信息
     * @return array|Json
     */
    public function information(){
        $data = Request::instance()->post();
        if (!empty($data)){
            $info = $data['data'];
            $info['is_complete'] = 1;
            $re = Db::name('user')
                ->where(['account'=>$info['account']])
                ->update($info);
            if ($re){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.mistake');
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 完善信息--获取邮编地址
     * @return array|Json
     */
    public function zipCode(){
        $data = Request::instance()->post();
        if (!empty($data['postcode'])){
            $code = str_replace(' ','',$data['postcode']);
            $re = Db::table('gb_postal_code')
                ->field('postal_code,place_name,admin_name1,admin_name2,admin_name3')
                ->where('postal_code','like',"{$code}%")
                ->where('admin_name3','<>','')
                ->select();
            foreach ($re as $k=>$v){
                if (!$v['admin_name1']){
                    $re[$k]['addr'] = $v['place_name'].','.$v['admin_name3'].','.$v['admin_name2'];
                }elseif (!$v['admin_name2']){
                    $re[$k]['addr'] = $v['place_name'].','.$v['admin_name3'].','.$v['admin_name1'];
                }elseif (!$v['admin_name3']){
                    $re[$k]['addr'] = $v['place_name'].','.$v['admin_name2'].','.$v['admin_name1'];
                }else{
                    $re[$k]['addr'] = $v['place_name'].','.$v['admin_name3'].','.$v['admin_name2'].','.$v['admin_name1'];
                }
            }
            if (false !== $re){
                $result = Config::get('code.success');
                $result['data']['list'] = $re;
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 验证码登录
     * @return array|Json
     */
    public function codeLogin(){
        $data = Request::instance()->post();
        if (!empty($data['account']) && !empty($data['code']) && !empty($data['type'])){
            $phoneNum = $data['account'];
            // 判断账号是否存在
            $user = Db::name('user')
                ->where(['account'=>$phoneNum])
                ->count();
            if($user==0){
                $result = Config::get('code.null');
                $result['msg'] = "账号不存在，请重新填写";
                return json($result);
            }
            $code = $data['code'];
            $sendCode = Session::get($phoneNum);
            $re = Db::name('user')
                ->where(['account'=>$phoneNum])
                ->find();
            if ($code == $sendCode && $re){
                // 生成新的token
                if ('APP' == $data['type']){
                    $token['app_token'] = randomNum();
                }else if ('WEB' == $data['type']){
                    $token['web_token'] = randomNum();
                }
                db('user')->where(['id'=>$re['id']])->update($token);
                $result = Config::get('code.success');
                $result['data'] = $re;
            }else{
                $result = Config::get('code.error');
                $result['msg'] = "账号或验证码错误";
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 找回密码
     * @return array|Json
     */
    public function pwdRest(){
        $data = Request::instance()->post();
        if (!empty($data['password']) && !empty($data['account']) && !empty($data['code'])){
            $phoneNum = $data['account'];
            $code = $data['code'];
            $sendCode = Session::get($phoneNum);
            if (null == $sendCode){
                $result = Config::get('code.error');
                $result['msg'] = "验证码不存在!";
                return json($sendCode);
            }
            // 检测输入的手机号是否已注册
            $re = Db::name('user')
                ->where(['account'=>$phoneNum])
                ->find();
            if (!$re){
                $result = Config::get('code.error');
                $result['msg'] = "手机号未注册!";
                return json($result);
            }
            if ($code == $sendCode){
                $password = md5($data['password']);
                $rePwd = Db::name('user')
                    ->where(['account'=>$phoneNum])
                    ->setField('password',$password);
                if (false !== $rePwd){
                    $result = Config::get('code.success');
                }else{
                    $result = Config::get('code.error');
                }
            }else{
                $result = Config::get('code.error');
                $result['msg'] = "验证码错误!";
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }


}